var express = require('express');
var query = require("../util/dbHelper.js");
var router = express.Router();

router.post("/add",(req,res,next)=> {
    if(req.body.id){//加数量
        req.myPromise = query('UPDATE `dt_mi_cart` SET num = ? WHERE `id` = ?;',[req.body.num,req.body.id])
            .then(result => {
                if(result.affectedRows === 1){//返回的数据库受影响的行
                    return {state:200,message:"添加成功",data:null};
                }else{
                    return {state:199,message:"添加失败",data:null};
                }
            });
        next();
    }else{
        let name = req.body.data.name,
            img = req.body.data.img,
            pid = req.body.data.pid,
            price = req.body.data.price,
            num = req.body.data.num,
            user = req.body.data.user;
        req.myPromise = query(
            'INSERT `dt_mi_cart`(`pid`,`user`,`num`,`price`,`name`,`img`) VALUES(?,?,?,?,?,?)',
            [ pid, user , num, price,name,img ]
        )
            .then(result => ({
                status: 200,
                message: '成功',
            }));
        next();
    }
});
//减少数量
router.post("/sub",(req,res,next)=>{
    if(req.body.id){//加数量
        req.myPromise = query('UPDATE `dt_mi_cart` SET num = ? WHERE `id` = ?;',[req.body.num,req.body.id])//查询数据库id相同的数据把num设置
            .then(result => {
                if(result.affectedRows === 1){//返回的数据库受影响的行
                    return {state:200,message:"添加成功",data:null};
                }else{
                    return {state:199,message:"添加失败",data:null};
                }
            });
        next();
    }
});
//查找该用户的购物信息
router.post('/init',(req,res,next)=>{
    let user = req.body.user;
        req.myPromise = query("SELECT * FROM `dt_mi_cart` WHERE `user` = ?;",[user])//调用sql函数，查询符合uName的
        .then(results => {
            return {status:200,message:"",data:results};
        });
    next();
});
router.post('/del',(req,res,next)=>{
    let id = req.body.id;//要删除的商品id
    req.myPromise = query("DELETE FROM `dt_mi_cart` WHERE `id` = ?;",[id])//获取提交过来的id
        .then(result => {
            if(result.affectedRows === 1){//返回的数据库受影响的行
                return {state:200,message:"删除成功",data:null};
            }
            else return{ state:199,message: "删除失败",data: null};
        });
    next();
});
module.exports = router;
